package com.leyou.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Configuration
public class RateLimitConfig {
    //定义一个KeyResolver
    @Bean
    public KeyResolver ipKeyResolver() {
        /*
        SpringCloudGateway中给桶信息存入Redis时需要有一个KEY来标记，key的生成规则定义在`KeyResolver`接口
         */
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                //给不同的请求IP地址设置不同令牌桶
                //mono未来返回，异步
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }
        };
        // JDK8 的Lambda写法：
        // return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }
}